package com.hu.juc.day01.T4;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * 题目:请举例说明集合类是不安全的
 * 1 故障现象
 * java.util.ConcurrentModificationException
 *
 * 2 导致原因
 *
 * 3 解决方案
 * 3.1  new Vector<>()
 * 3.2  Collections.synchronizedList(new ArrayList<>())
 * 3.3  new CopyOnWriteArrayList<>()
 *
 * 4 优化建议(同样的错误，不出现第2次)
 *
 * **笔记**
 * 写时复制
 * CopyOnwrite容器即写时复制的容器。往一个容器添加元素的时候，不直接往当前容器object[]添加，而是先将当前容器object[]进行Copy,
 * 复制出一个新的容器object[] newElements，然后新的容器object[] newElements里添加元素，添加完元素之后，
 * 再将原容器的引用指向新的容器setArray(newElements);。这样做的好处是可以对CopyOnWrite容器进行并发的读,
 * 而不需要加锁，因为当前容器不会添加任何元素。所以CopyOnWrite容器也是一种读写分离的思想，读和写不同的容器。
 *     public boolean add(E e) {
 *        final ReentrantLock lock = this.lock;
 *        lock.lock();
 *        try {
 *            object[] ele ments = getArray();
 *            int len = elements.Length;
 *            object[] newElements = Arrays.copyOf(elements, len + 1);
 *            newELements[len] = e;
 *            setArray(newElements);
 *            return true;
 *        finally{
 *                lock.unlock();
 *            }
 *        }
 *    }
 */
public class NotSafeDemo {
    public static void main(String[] args) {
        //HashMap底层是数组+链表+红黑树
        Map<String, String> map = new ConcurrentHashMap<>();//Collections.singletonMap();//new HashMap(16，0.75);
        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0, 8));
                System.out.println(map);
            }, String.valueOf(i)).start();
        }
    }

    /**
     * HashSet底层是HashMap
     * set.add(k) = map.put(k,v) ==> 此时v为一个Object类型的常量
     */
    private static void setNotSafe() {
        Set<String> set = new CopyOnWriteArraySet<>();//Collections.synchronizedSet();//new HashSet<>();
        for (int i = 1; i <= 30; i++) {
            new Thread(() -> {
                set.add(UUID.randomUUID().toString().substring(0, 8));
                System.out.println(set);
            }, String.valueOf(i)).start();
        }
    }


    private static void listNotSafe() {
        //List<String> list = new ArrayList<>();//public boolean add(E e) {}
        //List<String> list = new Vector<>();//public synchronized boolean add(E e) {}
        //List<String> list = Collections.synchronizedList(new ArrayList<>());
        List<String> list = new CopyOnWriteArrayList<>();

        //List<String> list = Arrays.asList("a", "b", "c");
        /*List<String> list = new ArrayList<>();
            list.add("a");
            list.add("b");
            list.add("c");*/
        //list.forEach(System.out::println);
        /*list.forEach((s)->{
            System.out.println(s);
        });*/

        for (int i = 1; i <= 30; i++) {
            new Thread(() -> {
                list.add(UUID.randomUUID().toString().substring(0, 8));
                System.out.println(list);
            }, String.valueOf(i)).start();
        }
    }
}